package io.kiki.sba.registry.server.shared.providedata;

import io.kiki.sba.registry.common.model.console.PersistenceData;
import io.kiki.sba.registry.common.model.constants.ValueConstants;
import io.kiki.sba.registry.server.shared.util.PersistenceDataParser;
import io.kiki.sba.registry.store.api.meta.ProvideDataRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class BaseStopPushService extends AbstractFetchPersistenceSystemProperty<BaseStopPushService.StopPushStorage, BaseStopPushService.StopPushStorage> {

    private static final Logger logger = LoggerFactory.getLogger(BaseStopPushService.class);
    private static final StopPushStorage INIT = new StopPushStorage(INIT_VERSION, false);
    @Autowired
    private ProvideDataRepository provideDataRepository;

    public BaseStopPushService() {
        // default value is stop.push
        super(ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, INIT);
    }

    @Override
    protected StopPushStorage fetchFromPersistence() {
        PersistenceData persistenceData = provideDataRepository.get(ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID);

        if (persistenceData == null) {
            return INIT;
        }
        return new StopPushStorage(persistenceData.getVersion(), PersistenceDataParser.parse2BoolIgnoreCase(persistenceData, INIT.stopPushSwitch));
    }

    @Override
    protected boolean doProcess(StopPushStorage expect, StopPushStorage update) {
        try {

            if (!compareAndSet(expect, update)) {
                logger.error("[FetchStopPushService]compareAndSet fail, expect={}/{}, update={}/{}", expect.getVersion(), expect.stopPushSwitch, update.getVersion(), update.stopPushSwitch);
                return false;
            }

            afterProcess(this.storage.get());
            logger.info("Fetch session stopPushSwitch={}, prev={}, current={}", update, expect.stopPushSwitch, update.stopPushSwitch);

            return true;
        } catch (Throwable e) {
            logger.error("Fetch session stopPushSwitch error.", e);
            return false;
        }
    }


    public boolean isStopPushSwitch() {
        return storage.get().stopPushSwitch;
    }

    protected void afterProcess(StopPushStorage storage) {
    }


    public void setStopPushSwitch(long version, boolean stopPushSwitch) {
        logger.info("set session stopPushSwitch, version={}, stopPushSwitch={}", version, stopPushSwitch);
        this.storage.set(new StopPushStorage(version, stopPushSwitch));
    }

    protected static class StopPushStorage extends SystemDataStorage {
        protected final boolean stopPushSwitch;

        public StopPushStorage(long version, boolean stopPushSwitch) {
            super(version);
            this.stopPushSwitch = stopPushSwitch;
        }

        public boolean isStopPush() {
            return stopPushSwitch;
        }
    }
}
